import hashlib
from io import BytesIO
import requests
import urllib3
from env.dev.config import EnvConfig
import ddddocr
from PIL import Image
from config import RunConfig
import logging

urllib3.disable_warnings()

# md5加密
def md5_encryption(password: str) -> str:
    return hashlib.md5(password.encode()).hexdigest()

def check_code(url: str) -> tuple:
    response = requests.get(url=url, verify=False)
    if response.status_code == 200:
        with open("./check_code.png", 'wb') as file:
            file.write(response.content)
    check_code_key = response.headers.get("Key")
    print("check code key:", check_code_key)
    image_data = response.content
    image = Image.open(BytesIO(image_data))
    # image.save("./check_code.png")
    try:
        ocr = ddddocr.DdddOcr(show_ad=False)
        ocr.classification(image_data)
        res = ocr.classification(image)
        print("check code num:", res)
        return (check_code_key, int(res))
    except Exception as e:
        print(e)
        return (check_code_key, 404)

def login():
    print("base url: ", EnvConfig.sign_in_url)
    print("check code url: ", EnvConfig.check_code_url)
    password = md5_encryption(EnvConfig.password)
    print("password: ", password)
    while True:
        check_code_key, check_code_num = check_code(EnvConfig.check_code_url)
        if check_code_num > 9999 or check_code_num < 1000:
            continue
        response = requests.post(
            url= EnvConfig.sign_in_url + "/user/sign/in",
            headers={
                "Content-Type": "application/json"
            },
            json={
                "password": password,
                "rememberMe": "false",
                "platform": "web",
                "key": check_code_key,
                "checkCode": check_code_num,
                "userName": EnvConfig.user_name,
            },
            verify=False
        )
        print("response: ", response.json())
        result = response.json()
        print("状态码： ", response.status_code)
        if response.status_code == 200:
            print("login success")
            break
    print("auth: ", result["result"].get("auth"))
    RunConfig.headers["Authorization"] = result["result"].get("auth")
    RunConfig.url = EnvConfig.sign_in_url
    return result["result"].get("auth")

if __name__ == "__main__":
    login()
